<template>
  <a-modal
    :visible="visible"
    width="800px"
    :title="title"
    :okText="okText"
    @cancel="cancel()"
    @ok="submit()"
  >
  <a-form :form="form">
      <a-form-item
        label="费率类型"
        :labelCol="{lg: {span: 7}, sm: {span: 7}}"
        :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
      >
        <a-radio-group
        v-model="feeRateType"
          @change="setFeeRateType"
        >
          <a-radio :value="1">固定</a-radio>
          <a-radio :value="2">阶梯</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        label="账单方式"
        :labelCol="{lg: {span: 7}, sm: {span: 7}}"
        :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
      >
        <a-radio-group
        v-model="feeMode">
          <a-radio :value="1">开票金额</a-radio>
          <a-radio :value="2">实发金额</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        label="服务费率"
        :labelCol="{lg: {span: 7}, sm: {span: 7}}"
        :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        v-if="feeRateType === 1"
      >
        <a-input-number
          :min="1"
          :max="20"
          :step="1"
          :formatter="value => `${value}%`"
          :parser="value => value.replace('%', '')"
          placeholder="服务费率"
          style="width: 100%;"
          v-model="feeRate"
        />
      </a-form-item>
      <a-form-item
        v-if="feeRateType === 2"
        label="阶梯费率"
        required
        :help="feeRangeValidator.help"
        :validate-status="feeRangeValidator.status"
        :labelCol="{lg: {span: 7}, sm: {span: 7}}"
        :wrapperCol="{lg: {span: 15}, sm: {span: 17} }"
      >
        <a-table
          v-show="feeRateRangeList.length"
          :columns="feeRateRangeColumns"
          rowKey="amountLow"
          :pagination="false"
          :data-source="feeRateRangeList"
          size="small"
        >
          <span
            slot="money"
            slot-scope="text">
            <span>{{ text | formatMoney }}</span>
          </span>
          <span
            slot="rate"
            slot-scope="text">
            <span>{{ parseFloat((text * 100).toFixed(10)) }}%</span>
          </span>
          <span
            slot="action"
            slot-scope="text, record, index">
            <template>
              <a @click="editFeeRate(record, index)">编辑</a>
            </template>
            <a-divider type="vertical" />
            <template >
              <a @click="deleteFeeRangeRow(index)">删除</a>
            </template>
          </span>
        </a-table>
        <a-button
          type="primary"
          @click="showCollectionModel">新增费率</a-button>
        <collection-create-form
          ref="collectionForm"
          :visible="collectionFormVisable"
          @cancel="handleCollectionCancel"
          @create="handleCollectionCreate"
        />
      </a-form-item>
      <a-form-item
          label="税率"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
          >
          <a-select
          v-model="taxRate"
              name="id"
              placeholder="请选择税率"
              @change="handleTaxRateChange">
              <a-select-option
              v-for="item in taxRateArr"
              :disabled="item.disabled"
              :key="item.value"
              :value="item.value">
              {{ item.label }}
              </a-select-option>
          </a-select>
      </a-form-item>
      <a-form-item
          v-if="xbdParams.isOpenXbd && xbdContractList.length > 0"
          label="薪八达合同uuid"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
          >
          <a-select
              v-model="xbdContractUuid"
              name="id"
              placeholder="请选择薪八达合同uuid"
              @change="handleXbdContractChange">
              <a-select-option
              v-for="item in xbdContractList"
              :key="item.xbdContractUuid"
              :value="item.xbdContractUuid">
              {{ item.xbdContractUuid }}
              </a-select-option>
          </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import {getFeeList, getXbdConcatList} from '@/api/manage'
import CollectionCreateForm from './feeRange-Form'
export default {
  components: {
    CollectionCreateForm
  },
  data () {
      return {
          feeOptions: [],
          arr: [],
          serverName: undefined,
          taxRate: undefined,
          xbdServerUuid: undefined,
          xbdContractUuid: undefined,
          serverId: '',
          feeRate: '',
          feeRateType: 1,
          feeMode: 2,
          collectionFormVisable: false,
          feeRateRangeList: [],
          feeRangeValidator: {
            status: 'error'
          },
          feeRateRangeColumns: [
            {
              title: '最低金额',
              dataIndex: 'amountLow',
              scopedSlots: { customRender: 'money' }
            },
            {
              title: '最高金额',
              dataIndex: 'amountHigh',
              scopedSlots: { customRender: 'money' }
            },
            {
              title: '服务费率',
              dataIndex: 'feeRate',
              scopedSlots: { customRender: 'rate' }
            },
            {
              title: '操作',
              dataIndex: 'action',
              scopedSlots: { customRender: 'action' }
            }
          ],
          currentIndex: -1,
          title: '新增供应商费率',
          okText: '新增',
          taxRateArr: [
              {
                  label: '6%',
                  value: '0.06',
                  disabled: false
              },
              {
                  label: '9%',
                  value: '0.09',
                  disabled: false
              },
              {
                  label: '13%',
                  value: '0.13',
                  disabled: false
              },
              {
                  label: '*',
                  value: '*',
                  disabled: false
              }
          ],
          visible: false,
          xbdParams: {
            isOpenXbd: false
          },
          havTaxRateArr: [],
          xbdContractList: []
      }
  },
  beforeCreate () {
    this.form = this.$form.createForm(this, { name: 'form_in_modal' })
  },
  mounted () {
    this.currentIndex = -1
      // this.getFeeLists()
  },
  methods: {
      // 税率改变
      handleTaxRateChange (e) {
          console.log(e)
      },
      // 薪八达合同改变
      handleXbdContractChange (e) {
        console.log(e)
      },
      show (info, havTaxRate, editInfo, index) {
        if (info.isOpenXbd) {
          this.xbdParams = info
          if (info.xbdServerUuid != '') {
            this.getXbdList()
          }
        }
        
        if (havTaxRate) {
          this.havTaxRateArr = havTaxRate.split(',')
          console.log(this.havTaxRateArr)
          console.log(this.taxRateArr)
          this.taxRateArr.forEach((item, index) => {
            this.havTaxRateArr.forEach(item1 => {
              if (item.value == item1) {
                this.$set(this.taxRateArr[index], 'disabled', true)
                // this.taxRateArr[index].disabled = true
              }
            })
          })
        } else {
          this.havTaxRateArr = []
          this.taxRateArr.forEach((item, index) => {
            this.$set(this.taxRateArr[index], 'disabled', false)
          })
        }
          this.visible = true
          if (editInfo) {
          this.edit(editInfo, index)
          // this.currentIndex = index
          // this.taxRate = editInfo.taxRate
          // this.feeRate = editInfo.feeRate
          // this.feeMode = editInfo.feeMode
          // this.feeRateType = editInfo.feeRateType
          // this.xbdContractUuid = editInfo.xbdContractUuid
          // if (editInfo.feeRateList) {
          //   this.feeRateRangeList = editInfo.feeRateList
          // }
          // feeMode: this.feeMode,
          //   feeRateType: this.feeRateType,
          //   feeRateList: [],
          //   taxRate: this.taxRate,
          //   xbdContractUuid: this.xbdContractUuid
        } else {
          this.feeRateType = 1
          this.taxRate = undefined
          this.xbdContractList = []
        }
      },
      getXbdList () {
        const params = {}
        getXbdConcatList(params).then(res => {
          console.log(res)
          if (res.resCode == '0000') {
            this.xbdContractList = res.resData
          }
        })
      },
      editFeeRate (info, index) {
          this.collectionFormVisable = true

          this.$refs.collectionForm.edit(info, index)
      },
    edit (info, index) {
      if (index != -1) {
        this.title = '修改供应商费率'
        this.okText = '保存'
        this.serverName = info.serverName
      this.serverId = info.serverId
      this.feeRate = info.feeRate
      this.feeRateType = info.feeRateType
      this.feeMode = info.feeMode
      this.taxRate = info.taxRate
      this.xbdContractUuid = info.xbdContractUuid
      if (info.feeRateList) {
        this.feeRateRangeList = info.feeRateList
      }
      this.currentIndex = index
      }
     
    },
    checkMinMax (rule, value, callback, source, options) {
      if (value <= this.form.getFieldValue('amountLow')) {
        callback(new Error('不应低于最低金额'))
      } else {
        callback()
      }
    },
    getInfo () {
      // console.log('ihao实际  ')
      this.currentIndex = -1
      this.feeMode = 2
      this.serverName = undefined
      this.serverId = ''
      this.feeRate = ''
      this.title = '新增供应商费率'
        this.okText = '新增'
      getFeeList().then(res => {
          console.log(res)
          this.feeOptions = res.resData
      }).catch(err => {
          console.log(err)
      })
    },
    handleServiceChange (e) {
      console.log(e)
      console.log(this.feeRate)
      this.feeOptions.forEach((i,index) => {
          if (e == i.id) {
              const obj = {}
              this.serverId = i.id
              // obj.feeMode = i.feeMode
              // obj.feeRateType = i.feeRateType
              // obj.feeRate = this.feeRate
              this.serverName = i.serverName
              // this.arr.push(obj)
          }
      })
    },
    submit () {
      console.log(this.feeRateRangeList)
      var infoObj = {}
      if (this.taxRate == undefined) {
        this.$message.error('请选择税率！')
        return
      }
      if (this.xbdParams.isOpenXbd && this.xbdContractList.length > 0) {
        if (this.xbdContractUuid == undefined) {
          this.$message.error('请选择薪八达合同uuid！')
          return
        }
      }
      if (this.feeRateType == 2) {
        if (this.feeRateRangeList.length > 0) {
          infoObj = {
          //   serverId: this.serverId,
          //   serverName: this.serverName,
            feeMode: this.feeMode,
            feeRateType: this.feeRateType,
            feeRateList: [],
            taxRate: this.taxRate,
            xbdContractUuid: this.xbdContractUuid
          }
          this.feeRateRangeList.forEach(i => {
            const obj = {
              amountLow: i.amountLow,
              amountHigh: i.amountHigh,
              feeRate: i.feeRate
            }
            infoObj.feeRateList.push(obj)
          })
        } else {
          this.$message.error('请先添加阶梯费率！')
          return
        }
      } else {
        if (!this.feeRate) {
          this.$message.error('请输入服务费率！')
          return
        }
        console.log(this.feeRate)
        infoObj = {
          // serverId: this.serverId,
          feeRate: this.feeRate,
          feeMode: this.feeMode,
          // serverName: this.serverName,
          feeRateType: this.feeRateType,
          taxRate: this.taxRate,
          xbdContractUuid: this.xbdContractUuid
        }
        // arr.push(obj)
      }
      this.$emit('finishPrice', infoObj, this.currentIndex)
      this.visible = false
      console.log(infoObj)
      
      this.serverName = undefined
      this.taxRate = undefined
      this.feeRate = ''
      this.feeRateRangeList = []
      this.xbdContractUuid = undefined
      this.xbdContractList = []
      this.currentIndex = -1
      // this.visible = false
      // this.handleCollectionCancel
      // return
      // this.arr[0].feeRate = this.feeRate
      // console.log(this.feeRate)
     
      // this.arr = []
      // this.serverName = undefined
      // this.feeRate = ''
      // console.log(this.form.getFieldValue())
    },
    cancel () {
      this.serverName = undefined
      this.taxRate = undefined
      this.feeRate = ''
      this.xbdContractUuid = undefined
      this.xbdContractList = []
      this.feeRateRangeList = []
      this.currentIndex = -1
      this.visible = false
    },
    setFeeRateType(event) {
      this.feeRateType = event.target.value
    },
    handleCollectionCancel() {
      this.$refs.collectionForm.form.resetFields()
      this.collectionFormVisable = false
    },
    handleCollectionCreate(index) {
      // index = this.currentIndex
      const form = this.$refs.collectionForm.form
      form.validateFields((err, values) => {
        if (err) {
          return
        }
        console.log(values)
       console.log(index)
        const arrayLength = this.feeRateRangeList.length
        if (index == -1) {
          if (
          arrayLength &&
          values.amountHigh * 100 !== this.feeRateRangeList[0].amountLow &&
          values.amountLow * 100 !== this.feeRateRangeList[arrayLength - 1].amountHigh
        ) {
          this.$message.error('请确保费率区间连续')
          return
        }
        }
        
        // console.log('Received values of form: ', values)
        values.amountHigh *= 100
        values.amountLow *= 100
        values.feeRate /= 100
        if (index == -1) {
        this.feeRateRangeList.push(values)

        } else {
          this.feeRateRangeList[index] = values
        }
        this.feeRateRangeList.sort((a, b) => a.amountLow - b.amountLow)
        console.log(this.feeRateRangeList)
        form.resetFields()
        this.checkFeeRange()
        this.collectionFormVisable = false
      })
    },
    showCollectionModel() {
      this.collectionFormVisable = true

      this.$refs.collectionForm.show()

      // this.$refs.collectionForm.add()
    },
    checkFeeRange() {
      if (this.feeRateRangeList.length) {
        this.feeRangeValidator = {
          help: '',
          status: 'success'
        }
      } else {
        this.feeRangeValidator = {
          help: '请添加阶梯费率',
          status: 'error'
        }
      }
    },
    deleteFeeRangeRow(index) {
      console.log(index)
      this.feeRateRangeList.splice(index, 1)
    }
  }
}
</script>
